package com.rover.system.controller;

import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.common.Common;
import com.grid.DataGrid;
import com.grid.Page;
import com.rover.system.entity.User;
import com.rover.system.service.SysParamService;
import com.rover.system.service.UserLogService;
import com.rover.system.service.UserRoleService;
import com.rover.system.service.UserService;
import com.utils.Encrypt;
import com.utils.JsonUtil;

/**
 * 用户
 */
@Controller
@RequestMapping("/userController")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private SysParamService sysParamService;

    @Autowired
    private UserLogService userLogService;

    @Autowired
    private UserRoleService userRoleService;

    // 用户登录
    @RequestMapping(value = {"/login"})
    public
    @ResponseBody
    Map<String, Object> login(HttpServletRequest request,
                              HttpServletResponse response) throws Exception {

        String userName = request.getParameter("name");
        String password = request.getParameter("pwd");
        String clientIp = request.getRemoteAddr();
        Map<String, Object> map = new HashMap<String, Object>();
        String msg = null;
        if (StringUtils.isNotBlank(userName)) {
            User user = userService.getUserByUserName(userName);
            if (user != null) {
                String originalPwd = user.getPassword();
                password = Encrypt.md5(password);
                if (originalPwd.equals(password)) {
                    int status = user.getStatus();
                    if (status == Common.ENABLE_STATUS) {// 启用
                    	 UsernamePasswordToken token = new UsernamePasswordToken(userName, password);
                         SecurityUtils.getSubject().login(token);
                         token.setRememberMe(Boolean.TRUE);
                        map.put("success", Boolean.TRUE);
                    } else {
                        // 未启用
                        map.put("success", Boolean.FALSE);
                        msg = "该用户未启用";
                    }
                } else {
                    // 密码不正确
                    map.put("success", Boolean.FALSE);
                    msg = "密码不正确";
                }
            } else {
                // 用户不存在
                map.put("success", Boolean.FALSE);
                msg = "用户不存在";
            }
        }
        map.put("message", msg);
        return map;
    }

    // 用户管理
    @RequestMapping("/query")
    @ResponseBody
    public Map<String, Object> query(HttpServletRequest request, Page page,
                                     HttpServletResponse response) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        String loginName = (String) request.getParameter("loginName");
        String hql = "";
        if (null != loginName) {
            hql = "where loginName like '%" + loginName + "%'";
        }
        Map<String, Object> params = new HashMap<String, Object>();

        DataGrid dataGrid = userService.query(page, params, hql);
        map = JsonUtil.JSONString(dataGrid.getResult(),
                dataGrid.getTotalCount());

        return map;
    }

    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> save(User user, HttpServletRequest request)
            throws Exception {
        // UserSession u = (UserSession)
        // request.getSession().getAttribute("userSession");
        Map<String, Object> map = new HashMap<String, Object>();
        Boolean success = true;
        String message = "";

        try {
            if (null == user.getId()) {
                success = userService.isAddNameRepeat(user.getLoginName());
            } else {
                success = userService.isEditNameRepeat(user.getLoginName(),
                        user.getId());
            }
            // 判断是否验证成功
            if (success) {
                userService.save(user);
            } else {
                message = "此用戶名称已存在，请重新输入！";
            }
            map.put("success", success);
            map.put("message", message);
        } catch (Exception e) {
            // logger.error(e.getMessage(), e);
            map.put("success", false);
            map.put("message", e.getMessage());
        }
        return map;
    }

    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> delete(@RequestParam("id") List<Integer> ids, HttpServletRequest request) {
        Map<String, Object> map = new HashMap<String, Object>();
        // String id = request.getParameter("id");
        try {
            for(Integer id:ids){
            //获取用户
            User u = userService.getUserById(id);
            //删除用户角色
            userRoleService.deleteRoles(u);
            //删除用户日志
            userLogService.deleteLogs(u);
            //刪除
            userService.delete(id);   }
            map.put("success", true);
            map.put("message", "");
        } catch (Exception e) {
            map.put("success", false);
            map.put("message", e.getMessage());
        }
        return map;
    }

    @RequestMapping(value = "/initPassword", method = RequestMethod.POST)
    @ResponseBody
    public void initPassword(@RequestParam("ids") String ids) {
        String[] userIds = ids.split(",");
        for (String id : userIds) {
            userService.initPassword(Integer.valueOf(id));
        }
    }

    // 密码修改
    @RequestMapping(value = "/savePwd", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> savePassword(HttpServletRequest request) {
    	Subject subject = SecurityUtils.getSubject();
		String loginName = (String) subject.getPrincipal();
		User user = userService.getUserByUserName(loginName);
        String password = request.getParameter("password");
        String newPwd = request.getParameter("newPwd");
        String newPwdTwo = request.getParameter("newPwdTwo");
        return userService.savePassword(user.getId(), password, newPwd,
                newPwdTwo);
    }

    // 注销
    @RequestMapping("/logout")
    public void logout(HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            Subject subject = SecurityUtils.getSubject();
            subject.logout();
            map.put("success", Boolean.TRUE);
        } catch (Exception e) {
            map.put("success", Boolean.FALSE);
            map.put("message", "注销失败");
        }

        JSONString(response, map);
    }

    public static void JSONString(
            HttpServletResponse response, Map<String, ? extends Object> data)
            throws Exception {
        String jsonObject = JSON.toJSONString(data);
        response.setContentType(Common.JSON_TYPE + ";charset="
                + Common.DEFAULT_ENCODING);
        response.setDateHeader("Expires", 0);
        response.addHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        PrintWriter out = response.getWriter();
        out.write(jsonObject);
    }

    // 启用禁用
    @RequestMapping("/enable")
    @ResponseBody
    public Map<String, Object> enable(@RequestParam("ids") String ids) {
        Map<String, Object> map = new HashMap<String, Object>();
        Boolean flag = Boolean.TRUE;
        map.put("success", flag);
        String[] idList = ids.split(",");
        for (String id : idList) {
            if (StringUtils.isBlank(id)) {
                continue;
            }
            User user = userService.getUserById(Integer.valueOf(id) );
            if (null != user) {
                int status = user.getStatus();
                if (status == 1) {
                    user.setStatus(Common.FORBIDDEN_STATUS);
                } else {
                    user.setStatus(Common.ENABLE_STATUS);
                }
                userService.saveEnable(user);
            }
        }
        return map;
    }

    // 重定向登陆页面
    @RequestMapping("/index")
    public String index() {
        return "redirect:login.jsp";
    }
}
